import type { RouteLocationNormalized } from 'vue-router'

export interface TagView {
  path: string
  name: string
  title: string
  fullPath: string
  isKeepAlive?: boolean
}

interface AppState {
  sidebar: {
    opened: boolean
    withoutAnimation: boolean
  }
  device: 'desktop' | 'mobile'
  tagView: TagView[]
  cachedViews: Map<string, string>
}

const appStore = defineStore('app', {
  // 存储数据state
  state: (): AppState => {
    return {
      sidebar: {
        opened: true,
        withoutAnimation: false,
      },
      device: 'desktop',
      tagView: [
        {
          path: '/index',
          name: 'index',
          title: '主页',
          fullPath: '/index',
          isKeepAlive: true,
        },
      ],
      // 缓存视图映射：path -> componentName，用于 keep-alive 缓存
      // 包含所有 isKeepAlive: true 的路由，不管 isTag 是否为 false
      cachedViews: new Map([['/index', 'index']]),
    }
  },
  // 配置持久化
  persist: {
    storage: localStorage,
    pick: ['opened'],
  },
  getters: {
    getVisitedViews: (state) => state.tagView,
    getCachedViews: (state) => Array.from(state.cachedViews.values()),
  },
  // 该函数没有上下文数据，所以获取state中的变量需要使用this
  actions: {
    // 切换侧边栏
    toggleSideBar(withoutAnimation: boolean) {
      this.sidebar.opened = !this.sidebar.opened
      this.sidebar.withoutAnimation = withoutAnimation
    },
    // 关闭侧边栏
    closeSideBar({ withoutAnimation }: { withoutAnimation: boolean }) {
      this.sidebar.opened = false
      this.sidebar.withoutAnimation = withoutAnimation
    },
    // 切换设备
    // 移动端切换为手机模式，侧边栏关闭
    toggleDevice(device: 'desktop' | 'mobile') {
      this.device = device
    },

    // 添加标签
    addView(view: RouteLocationNormalized) {
      const routeName = (typeof view.name === 'string' ? view.name : '') || view.path
      const isKeepAlive = view.meta?.isKeepAlive === true

      // 处理缓存视图（不管 isTag 是否为 false，只要 isKeepAlive 为 true 就缓存）
      if (isKeepAlive && routeName) {
        this.cachedViews.set(view.path, routeName)
      } else {
        // 如果 isKeepAlive 为 false，移除缓存
        this.cachedViews.delete(view.path)
      }

      // 处理标签视图（只有 isTag 不为 false 的才显示标签）
      if (view.meta?.isTag === false) {
        // 如果 isTag 为 false，移除已存在的标签（如果存在）
        const index = this.tagView.findIndex((v) => v.path === view.path)
        if (index > -1 && view.path !== '/index') {
          this.tagView.splice(index, 1)
        }
        return
      }

      // 如果已经存在，更新标签信息（保持最新的 meta 信息）
      const existingIndex = this.tagView.findIndex((v) => v.path === view.path)
      if (existingIndex > -1) {
        // 更新标签信息
        this.tagView[existingIndex] = {
          path: view.path,
          name: routeName,
          title: (view.meta?.title as string) || routeName,
          fullPath: view.fullPath,
          isKeepAlive,
        }
        return
      }

      // 添加到标签列表
      this.tagView.push({
        path: view.path,
        name: routeName,
        title: (view.meta?.title as string) || routeName,
        fullPath: view.fullPath,
        isKeepAlive,
      })
    },

    // 删除标签
    delView(view: TagView) {
      // 主页标签不可删除
      if (view.path === '/index') {
        return
      }

      const index = this.tagView.findIndex((v) => v.path === view.path)
      if (index > -1) {
        this.tagView.splice(index, 1)
      }

      // 同时移除缓存（如果存在）
      this.cachedViews.delete(view.path)
    },

    // 删除其他标签（除了当前标签）
    delOthersViews(view: TagView) {
      // 保留主页和当前标签
      this.tagView = this.tagView.filter((v) => v.path === '/index' || v.path === view.path)
    },

    // 删除所有标签（除了主页）
    delAllViews() {
      this.tagView = this.tagView.filter((v) => v.path === '/index')
    },
  },
})

// 对外暴露方法
export default appStore
